//
//  TMNetworkManage.m
//  TMBD Movie App
//
//  Created by zhangkai on 2023/4/22.
//

#import "TMNetworkManage.h"
#import <AdSupport/AdSupport.h>
#import "sys/utsname.h"
#import "movieInfo-Swift.h"
//#import "JavaScriptCore.h"
#import <JavaScriptCore/JavaScriptCore.h>

@implementation TMNetworkManage

+ (instancetype)defaultManager;{
    
    static TMNetworkManage *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[TMNetworkManage alloc] init];
        manager.sessionManager = [AFHTTPSessionManager manager];
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
        manager.sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.sessionManager.responseSerializer = responseSerializer;
        manager.sessionManager.requestSerializer.timeoutInterval = 20;
        manager.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json",nil];
//        manager.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];
        
        
//        这个格式要记得 有的后台不符合
//        manager.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        
    });
    
    return manager;
    
    
}

///公共参数
- (NSMutableDictionary *)generateCommonParamsWithApiName
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    [params setValue:@"" forKey:@"apns_id"];
    //需要改
    [params setValue:@"265" forKey:@"app_id"];
    //需要改
    [params setValue:@"1.2.0" forKey:@"app_ver"];
//    UIDevice.current.model
    
    [params setValue:[UIDevice currentDevice].model forKey:@"brand"];
    [params setValue:@"US" forKey:@"country"];
    [params setValue:[UIDevice currentDevice].systemName forKey:@"device"];
    
    [params setValue:[TMDeviceInfo deviceNo] forKey:@"deviceNo"];
    
//    ASIdentifierManager.shared().advertisingIdentifier.uuidString
    [params setValue:[ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString forKey:@"idfa"];
    
    [params setValue:[self getimsi] forKey:@"imsi"];
    
    [params setValue:@"0" forKey:@"installTime"];
    
    
//    NSLocale.preferredLanguages.first!
    NSString *lang = [NSLocale preferredLanguages].firstObject;
    [params setValue:lang forKey:@"lang"];
    
    [params setValue:[TMDeviceInfo model] forKey:@"model"];
    
    [params setValue:[TMDeviceInfo systemVersion] forKey:@"os_ver"];

    [params setValue: [TMDeviceInfo prefer] forKey:@"prefer"];
    
    [params setValue:@"100" forKey:@"r1"];
    
    NSString *resolution = @"1179x2556";
    [params setValue:resolution forKey:@"resolution"];
    [params setValue:@"0" forKey:@"simcard"];
    [params setValue:@"3" forKey:@"stageflag"];
    
    [params setValue:[TMDeviceInfo timezone] forKey:@"timezone"];
    
    [params setValue:@"1" forKey:@"token"];
    
    [params setValue:@"0" forKey:@"uid"];
    
    [params setValue:@"4.0" forKey:@"version"];
    
    [params setValue:@"0" forKey:@"vp"];
       
    return params;
}

- (NSString *)getParStrWithParams:(NSMutableDictionary *)params
{
    NSMutableString *temp = [NSMutableString string];
    NSArray *arr = params.allKeys;
    for (NSString *str  in arr) {
        [temp appendString:str];
        [temp appendString:@"="];
        id val = params[str];
        if ([val isKindOfClass:[NSString class]]) {
            [temp appendString:params[str]];
        }else if ([val isKindOfClass:[NSNumber class]]){
            [temp appendString:[val stringValue]];
        }
        [temp appendString:@"&"];
    }
    return [temp substringToIndex:temp.length - 1];
}

///拼接url
- (NSString *)generateRequestURLWithApiName:(NSString *)apiName {
    return [NSString stringWithFormat:@"%@/%@", @"", apiName];
}





///加密
- (void)MVWithApiName:(NSString * _Nullable)apiName
                    parameters:(id _Nullable)parameters
                       success:(vcsuccess)success
                       failure:(vcfailure)failure;{
    
    NSMutableDictionary *params = [self generateCommonParamsWithApiName];
    [params addEntriesFromDictionary:parameters];

    [self HTTPRequestWithURLString:[self generateRequestURLWithApiName:apiName] parameters:params success:success failure:failure];
    
    
}
- (void)MVGetWithApiName:(NSString * _Nullable)apiName
                    parameters:(id _Nullable)parameters
                       success:(vcsuccess)success
                       failure:(vcfailure)failure;{
    
    [self HTTPGetRequestWithURLString:[self generateRequestURLWithApiName:apiName] parameters:parameters success:success failure:failure];
}


///post请求
- (void)HTTPRequestWithURLString:(NSString *)URLString
                      parameters:(id)parameters
                         success:(vcsuccess)success
                         failure:(vcfailure)failure {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];
    [params setValue:@"keep-alive" forKey:@"Connection"];
    [params setValue:@"*/*" forKey:@"Accept"];
    NSString *Agent = [NSString stringWithFormat:@"Zefix/1.0.0 (iPhone;iOS %@; Scale/%.1f",[TMDeviceInfo systemVersion],[[UIScreen mainScreen] scale]];
    [params setValue:Agent forKey:@"User-Agent"];
    [params setValue:@"zh-Hans-CN;q=1, en-CN;q=0.9, zh-Hant-HK;q=0.8" forKey:@"Accept-Language"];
    [params setValue:@"571" forKey:@"Content-Length"];
    [params setValue:@"gzip, deflate" forKey:@"Accept-Encoding"];



    [_sessionManager POST:URLString parameters:parameters headers:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        success(task,responseObject);
    } failure:failure];

}

- (void)HTTPGetRequestWithURLString:(NSString *)URLString
                      parameters:(id)parameters
                         success:(vcsuccess)success
                         failure:(vcfailure)failure {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];
    [params setValue:@"keep-alive" forKey:@"Connection"];
    [params setValue:@"*/*" forKey:@"Accept"];
    NSString *Agent = [NSString stringWithFormat:@"Zefix/1.0.0 (iPhone;iOS %@; Scale/%.1f",[TMDeviceInfo systemVersion],[[UIScreen mainScreen] scale]];
    [params setValue:Agent forKey:@"User-Agent"];
    [params setValue:@"zh-Hans-CN;q=1, en-CN;q=0.9, zh-Hant-HK;q=0.8" forKey:@"Accept-Language"];
    [params setValue:@"571" forKey:@"Content-Length"];
    [params setValue:@"gzip, deflate" forKey:@"Accept-Encoding"];
    

    [_sessionManager GET:URLString parameters:parameters headers:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(task,responseObject);
    } failure:failure];
    

}



//请求参数
//- (NSString *)getUUID{
//
//    NSString *cur = [[NSUserDefaults standardUserDefaults] stringForKey:@"uuidstr"];
//
//    if(cur.length > 0){
//        return cur;
//    }else{
//        NSString *str = [[NSUUID new] UUIDString];
//        [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"uuidstr"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//
//        return str;
//
//    }
//
//}

- (NSString *)getimsi{
    
    
    NSString *cur = [[NSUserDefaults standardUserDefaults] stringForKey:@"imsiStr"];
    if(cur.length > 0){
        return cur;
    }else{
        
        NSArray *arr = @[@"52501",@"52503",@"310200",@"52502",@"310010",@"310210",@"310220",@"310170",@"50501",@"23430",@"23433",@"23415",@"23410",@"20404",@"24101"];
        
        
       
        NSInteger index =  arc4random() % arr.count;
        NSString *str = arr[index];
        
        [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"imsiStr"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        return str;
        
    }

    
    
//    let nums = ["52501","52502","52503","310010","310200","310210","310220","310170","50501","24101","20404","23410","23415","23433","23430"]
//    var num = UserDefaults.standard.object(forKey: "device_imsiKey")
//    if num == nil {
//        let i:Int = Int(arc4random() % 14)
//        num = nums[i]
//        UserDefaults.standard.setValue(num, forKey: "device_imsiKey")
//    }
//    return num as! String
}


- (NSString *)getencry:(NSString *)jiamiStr{
    
    JSVirtualMachine *mach = [JSVirtualMachine new];
    JSContext *ext = [[JSContext alloc] initWithVirtualMachine:mach];
    NSString *cur = [[NSUserDefaults standardUserDefaults] stringForKey:@"ttjiami"];
    if(cur.length > 0){
        
        NSString *filestr = @"/encryptionFunc.js";
        NSString *fil =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *path = [NSString stringWithFormat:@"%@%@",fil,filestr];
        NSError *error = nil;
        NSString *scri = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        
        [ext evaluateScript:scri];
        JSValue *funcva = [ext objectForKeyedSubscript:cur];
        JSValue *result = [funcva callWithArguments:@[jiamiStr]];
        return  [result toString];

    }else{
        cur = @"ue";
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"TTJiaMi" ofType:nil];
        NSError *error = nil;
        NSString *scri = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
        [ext evaluateScript:scri];
        JSValue *funcva = [ext objectForKeyedSubscript:cur];
        JSValue *result = [funcva callWithArguments:@[jiamiStr]];
        return  [result toString];
    }
    
   
}


- (NSString *)getsigencry:(NSString *)jiamiStr;{
    
    
    JSVirtualMachine *mach = [JSVirtualMachine new];
    JSContext *ext = [[JSContext alloc] initWithVirtualMachine:mach];
    NSString *cur = [[NSUserDefaults standardUserDefaults] stringForKey:@"ttsigjiami"];
    if(cur.length > 0){
        
        NSString *filestr = @"/encryptionFunc.js";
        NSString *fil =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *path = [NSString stringWithFormat:@"%@%@",fil,filestr];
        NSError *error = nil;
        NSString *scri = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        
        [ext evaluateScript:scri];
        JSValue *funcva = [ext objectForKeyedSubscript:cur];
        JSValue *result = [funcva callWithArguments:@[jiamiStr]];
        return  [result toString];

    }else{
        cur = @"Ta";
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"TTJiaMi" ofType:nil];
        NSError *error = nil;
        NSString *scri = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
        [ext evaluateScript:scri];
        JSValue *funcva = [ext objectForKeyedSubscript:cur];
        JSValue *result = [funcva callWithArguments:@[jiamiStr]];
        return  [result toString];
    }
    
    
}

@end
